package com.filetransfer.app.ui.setting

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.filetransfer.app.databinding.FragmentSettingBinding
import com.filetransfer.app.ui.upload.UploadActivity

class SettingFragment : Fragment() {
    private var _binding: FragmentSettingBinding? = null
    private val binding get() = _binding!!
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val settingViewModel = ViewModelProvider(this).get(SettingViewModel::class.java)

        _binding = FragmentSettingBinding.inflate(inflater, container, false)
        val root: View = binding.root
        // 绑定UI组件
        val loginButton: Button = binding.buttonLogin
        val myFilesButton: Button = binding.buttonMyFiles
        val getCodeButton: Button = binding.buttonGetCode
        val downloadClientButton: Button = binding.buttonDownloadClient
        val themeButton: Button = binding.buttonTheme
        // 设置按钮点击事件
        loginButton.setOnClickListener {
            showLoginDialog()
        }

        myFilesButton.setOnClickListener {
            chooseFile()
        }

        getCodeButton.setOnClickListener {
            Toast.makeText(requireContext(), "获取发送码功能暂未实现", Toast.LENGTH_SHORT).show()
        }

        downloadClientButton.setOnClickListener {
            showDownloadDialog()
        }

        themeButton.setOnClickListener {
            showSettingsDialog()
        }

        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun chooseFile() {
        val intent = Intent(requireContext(), UploadActivity::class.java)
        startActivity(intent)
    }

    private fun saveThemePreference(theme: String) {
        val sharedPreferences =
            requireContext().getSharedPreferences("app_theme", android.content.Context.MODE_PRIVATE)
        sharedPreferences.edit().putString("selected_theme", theme).apply()
    }

    private fun loadThemePreference(): String {
        val sharedPreferences =
            requireContext().getSharedPreferences("app_theme", android.content.Context.MODE_PRIVATE)
        return sharedPreferences.getString("selected_theme", "AppTheme.Base") ?: "AppTheme.Base"
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        val theme = loadThemePreference()
        requireActivity().setTheme(
            resources.getIdentifier(
                theme,
                "style",
                requireContext().packageName
            )
        )
    }
    // 登录弹窗
    private fun showLoginDialog() {
        val usernameField = EditText(requireContext())
        usernameField.hint = "请输入账号"
        val passwordField = EditText(requireContext())
        passwordField.hint = "请输入密码"
        passwordField.inputType =
            InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
        val layout = LinearLayout(requireContext())
        layout.orientation = LinearLayout.VERTICAL
        layout.addView(usernameField)
        layout.addView(passwordField)
        val builder = AlertDialog.Builder(requireContext())
        builder.setTitle("登录")
            .setView(layout)
            .setPositiveButton("登录") { dialog, _ ->
                val username = usernameField.text.toString().trim()
                val password = passwordField.text.toString().trim()
                if (username.isEmpty() || password.isEmpty()) {
                    Toast.makeText(requireContext(), "请输入账号和密码！", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(requireContext(), "登录成功！", Toast.LENGTH_SHORT).show()
                    dialog.dismiss()
                }
            }
            .setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
        builder.create().show()
    }
    // 显示PC端网址的对话框
    private fun showDownloadDialog() {
        val urlField = EditText(requireContext())
        urlField.setText("https://www.pcwebsite.com")
        urlField.isEnabled = false
        val builder = AlertDialog.Builder(requireContext())
        builder.setTitle("PC端网址")
            .setView(urlField)
            .setPositiveButton("确定") { dialog, _ -> dialog.dismiss() }
            .setCancelable(true)
        builder.create().show()
    }

    private fun showSettingsDialog() {
        val builder = AlertDialog.Builder(requireContext())
        builder.setTitle("选择主题")
            .setItems(arrayOf("默认", "深色主题", "浅色主题")) { _, which ->
                when (which) {
                    0 -> saveThemePreference("AppTheme.Base")
                    1 -> saveThemePreference("AppTheme.Dark")
                    2 -> saveThemePreference("AppTheme.Light")
                }
                requireActivity().recreate()  // 重新启动以应用主题
            }
            .setCancelable(true)
            .create()
            .show()
    }
}
